package org.jawa.learning.service.impl;

import java.util.List;

import org.jawa.core.exception.AlreadyExistsException;
import org.jawa.core.exception.UserNotFoundException;
import org.jawa.learning.dao.UserDao;
import org.jawa.learning.model.User;
import org.jawa.learning.service.UserManager;
import org.jawa.learning.webapp.util.Page;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;


/**
 * Implementation of UserManager interface.
 *
 * @author <a href="mailto:matt@raibledesigns.com">Matt Raible</a>
 */
@Service("userManager")
public class UserManagerImpl extends GenericManagerImpl<User, Long> implements UserManager {

	private UserDao userDao;

    @Autowired
    public void setUserDao(UserDao userDao) {
        this.dao = userDao;
        this.userDao = userDao;
    }

    /**
     * {@inheritDoc}
     */
    public User getUser(String userId) {
        return userDao.get(new Long(userId));
    }

    /**
     * {@inheritDoc}
     */
    public List<User> getUsers() {
        return userDao.getAllDistinct();
    }

    /**
     * {@inheritDoc}
     */
    public Page<User> getUsers(User user,Page<User> page) {
        return userDao.getUsers(user,page);
    }
    
    /**
     * {@inheritDoc}
     */
    public User saveUser(User user) throws AlreadyExistsException {
        try {
            return userDao.saveUser(user);
        } catch (Exception e) {
            log.warn(e.getMessage());
            throw new AlreadyExistsException("User '" + user.getUsername() + "' already exists!");
        } 
    }

    public User updateUser(User user) throws Exception{
      return userDao.updateUser(user);
    }
    
    /**
     * {@inheritDoc}
     */
    public void removeUser(String userId) {
        log.debug("removing user: " + userId);
        userDao.remove(new Long(userId));
    }

    /**
     * {@inheritDoc}
     *
     * @param username the login name of the human
     * @return User the populated user object
     * @throws UsernameNotFoundException thrown when username not found
     */
    public User getUserByUsername(String username) throws UserNotFoundException {
        return (User) userDao.loadUserByUsername(username);
    }

}
